package hr.mlab.app.expenses.activities.transaction;

import hr.mlab.app.expenses.AppGlobals;
import hr.mlab.app.expenses.DatabaseOpenHelper;
import hr.mlab.app.expenses.R;
import android.app.Activity;
import android.app.ListActivity;
import android.content.Intent;
import android.database.Cursor;
import android.database.sqlite.SQLiteDatabase;
import android.os.Bundle;
import android.view.Menu;
import android.view.MenuInflater;
import android.view.MenuItem;
import android.view.View;
import android.widget.ListAdapter;
import android.widget.ListView;
import android.widget.SimpleCursorAdapter;

public class TransactionList extends ListActivity {
    private SQLiteDatabase db;
    private Integer groupId;
    private Integer typeId;
    private Integer fromDay;
    private Integer fromMonth;
    private Integer fromYear;
    private Integer fromDate;
    private Integer untilDay;
    private Integer untilMonth;
    private Integer untilYear;
    private Integer untilDate;
    private Cursor cursor=null;
    private ListAdapter adapter;
    private Boolean fromItemClick=false;
    
    /** Called when the activity is first created. */
    @Override    
    public void onCreate(Bundle savedInstanceState) {
    	super.onCreate(savedInstanceState);
    	setContentView(R.layout.transactionlist);
    	db = (new DatabaseOpenHelper(this)).getReadableDatabase();
    	
    	// get input parameters
    	groupId    	= getIntent().getIntExtra("groupId", 0);
    	typeId     	= getIntent().getIntExtra("typeId", 0);
    	fromDay		= getIntent().getIntExtra("fromDateDay", 1);
    	fromMonth	= getIntent().getIntExtra("fromDateMonth", 1);
    	fromYear	= getIntent().getIntExtra("fromDateYear", 2000);
    	untilDay 	= getIntent().getIntExtra("untilDateDay", 1);
    	untilMonth	= getIntent().getIntExtra("untilDateMonth", 1);
    	untilYear	= getIntent().getIntExtra("untilDateYear", 2000);
    	
    	fromDate	= fromYear * 10000 + fromMonth * 100 + fromDay;
    	untilDate	= untilYear * 10000 + untilMonth * 100 + untilDay;

    	fillListView();
    }

    /**
     * Closing activity
     */
    @Override    
    public void onDestroy() {
    	super.onDestroy();
    	cursor.close();
    	db.close();
    }

    /**
     * Filling list
     * @param view
     */
    public void fillListView() {
    	if(cursor != null)
    		if(!cursor.isClosed()) 
    			cursor.close();
    	
    	cursor = db.rawQuery("SELECT _id, comment, (transactionYear * 10000 + transactionMonth * 100 + transactionDay) as transactionDate, " +
				   			 "transactionAmount FROM " + DatabaseOpenHelper.dbTransactions + " " +
				   			 "WHERE groupId = ? and typeId = ? and (transactionYear * 10000 + transactionMonth * 100 + transactionDay) " +
				   			 "between ? and ? order by transactionYear, transactionMonth, transactionDay", 
    						 new String[]{groupId.toString(), typeId.toString(), fromDate.toString(), untilDate.toString()});

        adapter = new SimpleCursorAdapter(
                            this, 
                            R.layout.transactionrow, 
                            cursor, 
                            new String[] {"comment", "transactionDate", "transactionAmount"}, 
                            new int[] {R.id.comment, R.id.date, R.id.amount});

        setListAdapter(adapter);
        registerForContextMenu(getListView());
    }

    /**
     * Catcher of list clicks
     * @param ListView parent, View view, int position, long id
     */
    public void onListItemClick(ListView parent, View view, int position, long id) {
    	groupId = (int) id;
    	fromItemClick = true;
    	((Activity) this).openOptionsMenu();
    }
    
 	/**
 	 * Menu initialization
 	 * @param menu
 	 */
 	@Override
 	public boolean onCreateOptionsMenu(Menu menu) {
 		MenuInflater inflater = getMenuInflater();
 		inflater.inflate(R.menu.newmenu, menu);
 		return true;
 	}
 	
 	/**
 	 * Changing a menu. We don't have fixed menu. It's changed depending on where it opens 
 	 * @param menu
 	 */
 	@Override
 	public boolean onPrepareOptionsMenu(Menu menu) {
 		menu.clear();
 		if(fromItemClick) {
 			menu.add(0, AppGlobals.optUpdate, 0, this.getString(R.string.btnUpdate));
 			menu.add(0, AppGlobals.optDetail, 0, this.getString(R.string.btnDetail));
 			menu.add(0, AppGlobals.optDelete, 0, this.getString(R.string.btnDelete));
 		} else {
 			menu.add(0, AppGlobals.optNew, 0, this.getString(R.string.btnNew));
 		}

 		fromItemClick = false;
 		
 		return super.onPrepareOptionsMenu(menu);
 	}

 	/**
 	 * Reaction to the menu selection
 	 * @param featureId, menuItem
 	 */
 	@Override
 	public boolean onMenuItemSelected(int featureId, MenuItem item) {
 		return super.onMenuItemSelected(featureId, item);
 	}

 	/**
 	 * Reaction to the option menu selection
 	 * @param menuItem
 	 */
 	@Override
 	public boolean onOptionsItemSelected(MenuItem item) {
		callGroupDetail(item.getItemId());
 		return super.onOptionsItemSelected(item);
 	}
 	
 	/**
 	 * Reaction to the context menu selection
 	 * @param menuItem
 	 */
	@Override
	public boolean onContextItemSelected(MenuItem item) {
		callGroupDetail(item.getItemId());
		return super.onContextItemSelected(item);
	}

	/**
	 * we need a handler when the secondary activity finishes it's work
	 * and returns control to this activity...
	 * @param requestCode, resultCode, intent
	 */
    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent intent){
    	super.onActivityResult(requestCode, resultCode, intent);
    	if(resultCode == Activity.RESULT_OK ) { 
    		fillListView();
    		setSelection(intent.getIntExtra("groupId", 0));
    	}
    }

    /**
     * Calling detail for category
     * @param menuItem - indicates option
     */
	public void callGroupDetail(int menuItem){
    	Intent intent = new Intent(this, TransactionDetail.class);
    	intent.putExtra("option", (byte) menuItem);
    	
    	if(menuItem > 1) {
    		intent.putExtra("groupId", groupId);
    	} else {
    		intent.putExtra("groupId", 0);
    	}
    	
    	startActivityForResult(intent, menuItem);
	}
}
